var common = function(){};
/**
 * layui 全选checkbox
 * @param string checkboxFilter 全选框触发lay-filter设置名
 * @param string checkboxName 勾选框name名
 */
common.selectCheckbox = function(checkboxFilter,checkboxName){
    //class为layui-form
    layui.use(['form'], function(){
        var form = layui.form;
        //全选按钮需要设置lay-filter=""
        form.on('checkbox('+checkboxFilter+')', function (data) {
            $("input[name='"+checkboxName+"']").each(function () {
                this.checked = data.elem.checked;
            });
            form.render('checkbox');
        });
    });
};
/**
 * jq 获取checkbox勾选值
 */
common.getCheckboxVal = function(){
    //获取checkbox值
    var checked = [];
    $("input:checkbox:checked").each(function(){
        checked.push($(this).val());
    });
    //去掉数组中空值，全选checkbox框需要value=""
    checked = checked.filter(item=>item);
    //join变成逗号分隔的字符串
    //checked.join(',')
    return checked;
};
/**
 * 设置多个日期控件
 */
common.setDateControls = function(dateArray){
    /*
        dateArray = [
            //json数组中放layui日期控件参数
            {elem: '#time', style: 'datetime', max: '23:59:59', type: 'datetime', format:'yyyy-MM-dd HH:mm:ss', trigger: 'click'}
        ]
    */
	layui.use(['laydate', 'form'], function(){
		var laydate = layui.laydate;
		dateArray.forEach(function(item, index){
            laydate.render(item);
		});
	})
};
/**
 * 设置日期区间，固定开始和结束
 */
common.setDate = function (max) {
    if(!max) max = "23:59:59"
    layui.use(['laydate','form'], function(){
        var laydate = layui.laydate;
        var form = layui.form;
        //执行一个laydate实例
        laydate.render({
            elem: '#start', //指定元素
            max: max,
			trigger: 'click'
        });
        //执行一个laydate实例
        laydate.render({
            elem: '#end', //指定元素
            max: max,
			trigger: 'click'
        });
        //监听提交
        form.on('submit(search)', function(data) {
            var info = data.field;
            if(info.start.length > 0){
                //开始日期
                if(info.start.length !== 10){
                    layer.msg('开始日期请填写正确', {icon: 5,time:1500});
                    return false
                }
                //截止日期
                if(info.end.length !== 10){
                    layer.msg('截止日期请填写正确', {icon: 5,time:1500});
                    return false
                }
                //开始时间不能大于截止日期
                if(info.start > info.end){
                    layer.msg('开始日期不能大于截止日期', {icon: 5,time:1500});
                    return false
                }
            }
        });
    });
};
/**
 * 树状菜单
 * @param array list 数据
 * @param array info 触发的dom json数组
 */
common.treeMenu = function(list, info){
    /*
        <div class="eleTree ele5" lay-filter="data5"></div>
        var info = {
            name:"role",                             //触发name
            className:".ele5",                       //显示class
            nodeClick:"data5",                       //点击lay-filter值
            js:"__components__/eleTree/",            //js路径
            inputId:"#roleId",                       //写入id
            multipleChoice:true,                     //是否多选
            selectedId:[1,2,3],                      //选择的id
            selectedLabel:['name1','name2','name3'], //选择的label
            checkStrictly: false                     //是否父子不互相关联
        }
     */
    layui.config({
        base: "/components/eleTree/" //js文件夹路径
    }).use(['jquery','eleTree'], function() {
        var $ = layui.jquery;
        var eleTree = layui.eleTree;

        var name = info.name;           //触发name
        var className = info.className; //显示class
        var nodeClick = info.nodeClick; //点击lay-filter值
        var checkStrictly = false        //是否父子不互相关联
        var multipleChoice;
        var selectedId;
        var selectedLabel;
        //是否多选
        if(info.multipleChoice){
            multipleChoice = info.multipleChoice
            //选中id数组
            info.selectedId ? selectedId = info.selectedId : selectedId = []
            //选中label值数组
            info.selectedLabel ? selectedLabel = info.selectedLabel : selectedLabel = []
        }else{
            multipleChoice = false
        }
        //是否父子不互相关联
        if(info.checkStrictly) checkStrictly = info.checkStrictly
        if(list.length <= 0){
            $(className).html("<div style='text-align: center'>暂无数据</div>")
            return
        }
        var ele;
        $("[name="+name+"]").on("click",function (e) {
            e.stopPropagation();
            ele = eleTree.render({
                elem: className,
                data: list,
                showCheckbox: multipleChoice, //节点是否可被选择
                checkStrictly: checkStrictly, //严格的遵循父子不互相关联的做法
                defaultCheckedKeys: selectedId, //默认展开的节点的 key 的数组
                defaultExpandAll: true, //默认展开所有节点
                expandOnClickNode: false, //点击节点的时候展开或者收缩节点
                checkOnClickNode: true, //是否在点击节点的时候选中节点
                highlightCurrent: true, //是否高亮当前选中节点
                showLine: true //是否显示连线
            });
            //toggle() 方法在被选元素上进行 hide() 和 show() 之间的切换。
            $(className).show();
            //单选时将已选数据填充背景
            let val = $(info.inputId).val()
            if(val && multipleChoice == false){
                $(".eleTree-node").each(function () {
                    let dataId = $(this).attr("data-id")
                    if(dataId == val) $(this).children().first().css({"background":"#009688", "color":"#fff"})
                })
            }
        });
        //如果是单选
        if(multipleChoice == false){
            // 节点点击事件
            eleTree.on("nodeClick("+nodeClick+")",function(d) {
                let data = d.data.currentData //数据
                if(!data.disabled){
                    //如果有inputId
                    if(info.inputId) $(info.inputId).val(d.data.currentData.id);
                    $("[name="+name+"]").val(d.data.currentData.label)
                    $(className).hide();
                }
            });
        //如果是多选
        }else{
            //选中事件
            eleTree.on("nodeChecked("+nodeClick+")",function(d) {
                //获取所有选中的数据
                let data = ele.getChecked(false, true)
                let id = []
                let value = []
                data.forEach(function (item, index) {
                    id.push(item.id)
                    value.push(item.label)
                })
                $(info.inputId).val(id.join(","));          //写入input id
                $("[name="+name+"]").val(value.join(","));  //写入input label
                selectedId = id                             //赋值给已选id
                selectedLabel = value                       //赋值已选label
            })
        }
        //点击外面隐藏
        $(document).on("click",function() {
            $(className).hide();
        });
    });
}
/**
 * 直接显示树状菜单
 * @param array list 数据
 * @param array info 触发的dom json数组
 */
common.treeMenuShow = function(list, info){
    /*
        <div class="eleTree ele2" lay-filter="data2"></div>
        var info = {
            className:".ele2",              //显示class
            nodeClick:"data2",              //点击lay-filter值
            js:"__components__/eleTree/",   //js路径
            inputId:"#roleId",              //写入id
            multipleChoice:true,            //是否多选
            selectedId:[1,2,3],             //选择的id
            checkStrictly: false            //是否父子不互相关联
        }
     */
    layui.config({
        base: "/components/eleTree/" //js文件夹路径
    }).use(['jquery','eleTree'], function() {
        var $ = layui.jquery;
        var eleTree = layui.eleTree;

        var className = info.className;         //显示class
        var nodeClick = info.nodeClick;         //点击lay-filter值
        var checkStrictly = false;              //是否父子不互相关联
        var multipleChoice;
        var selectedId;
        //是否多选
        if(info.multipleChoice){
            multipleChoice = info.multipleChoice
            //选中id数组
            info.selectedId ? selectedId = info.selectedId : selectedId = []
        }else{
            multipleChoice = false
        }
        //是否父子不互相关联
        if(info.checkStrictly) checkStrictly = info.checkStrictly
        if(list.length <= 0){
            $(className).html("<div style='text-align: center'>暂无数据</div>")
            return
        }
        var ele = eleTree.render({
            elem: className,
            data: list,
            showCheckbox: multipleChoice, //节点是否可被选择
            checkStrictly: checkStrictly, //严格的遵循父子不互相关联的做法
            defaultCheckedKeys: selectedId, //默认展开的节点的 key 的数组
            defaultExpandAll: true, //默认展开所有节点
            expandOnClickNode: false, //点击节点的时候展开或者收缩节点
            checkOnClickNode: true, //是否在点击节点的时候选中节点
            highlightCurrent: true, //是否高亮当前选中节点
            showLine: true //是否显示连线
        });
        //单选时将已选数据填充背景
        let val = $(info.inputId).val()
        if(val && multipleChoice == false){
            $(".eleTree-node").each(function () {
                let dataId = $(this).attr("data-id")
                if(dataId == val) $(this).children().first().css({"background":"#009688", "color":"#fff"})
            })
        }
        //如果是单选
        if(multipleChoice == false){
            // 节点点击事件
            eleTree.on("nodeClick("+nodeClick+")",function(d) {
                let data = d.data.currentData //数据
                if(!data.disabled){
                    //如果有inputId
                    if(info.inputId) $(info.inputId).val(d.data.currentData.id);
                }
            });
        //如果是多选
        }else{
            //选中事件
            eleTree.on("nodeChecked("+nodeClick+")",function(d) {
                //获取所有选中的数据
                let data = ele.getChecked(false, true)
                let id = []
                let value = []
                data.forEach(function (item, index) {
                    id.push(item.id)
                    value.push(item.label)
                })
                $(info.inputId).val(id.join(",")); //写入input id
            })
        }
    });
};
/**
 * 获取树状菜单列表
 * @param string url 请求地址{:url('Article/getClassify')}
 */
common.getTreeMenuList = function(url){
    var list = [];
    //获取所有分类
    $.ajax({
        type: "post",
        url: url,
        dataType: 'json',
        async: false,
        success:function (data) {
            if(data.status == 0){
                setTimeout(function () {
                    layer.msg(data.info + " 分类信息", {icon: 5,time:1500});
                }, 1000)
            }else{
                list = data;
            }
        },
        error:function (data) {
            console.log(data);
            layer.msg("不好意思，出现了一点问题", {icon: 5,time:1500});
        }
    });
    return list;
};
/**
 * 数据导出
 * @param array info 发送的数据
 * @param string url 请求地址
 * @param string unlink 删除服务器文件地址
 */
common.dataExport = function(info, url, unlink){
    layer.msg('正在导出，请稍后...', {
        time: 1000, //1s后自动关闭
        end: function(layero, index){ //层销毁后执行
            var index = layer.load();
            $.ajax({
                type: 'POST',//提交方式 post 或者get
                url: url,//提交到那里
                data: info,
                dataType: 'json',
                success:function(data){
                    if(data.status == 1){
                        layer.open({
                            type: 1,
                            title: false,
                            closeBtn: 0,
                            shadeClose: true,
                            area: ['300px', '130px'],
                            skin: 'yourclass',
                            content: data.info,
                            end: function(layero, index){
                                $.post(unlink, {link: data.url});
                            }
                        });
                    }else{
                        layer.msg(data.info,{time:1500, icon:5});
                    }
                    layer.close(index);
                },
                error:function(data){
                    layer.close(index);
                }
            });
        }
    });
};
/**
 * 弹出iframe窗口
 * @param string title 标题
 * @param string url 跳转链接
 * @param int w 宽
 * @param int h 高
 * @param boolean isMax 是否显示最大化按钮
 * @param boolean full 是否弹窗最大化
 */
common.openWindow = function(title, url, w, h, isMax=false, full=false){
    //标题
    if (title == null || title == '') {
        var title = false;
    }
    //链接地址
    if (url == null || url == '') {
        var url = "404.html";
    }
    //宽度
    if (w == null || w == '') {
        var w = ($(window).width() * 0.9);
    }
    //高度
    if (h == null || h == '') {
        if(full){
            var h = ($(window).height());
        }else{
            var h = ($(window).height() -50);
        }
    }
    var index = layer.open({
        type: 2,
        area: [w +'px', h +'px'],
        fix: false, //不固定
        maxmin: isMax, //显示最大化按钮
        shadeClose: true, //点击遮罩关闭
        shade:0.4,  //遮罩透明度
        anim: 2,
        title: title,
        content: url
    });
    if(full){
        layer.full(index);
    }
};
/**
 * 加载城市
 * @param int filter lay-filter 选择lay-filter="province"
 * @param string url 请求地址
 */
common.getCity = function(filter, url, loadId) {
    layui.use(['form'], function() {
        var form = layui.form;
        //加载城市
        form.on('select('+filter+')', function (data) {
            //获取省份or城市id select需要设置加载的level，如 <select level="3" name="city" id="city">
            var level = $("#"+data.elem.id).attr('level');
            //父id
            var parentId = data.value;
            //提交数据
            $.ajax({
                type: 'POST',//提交方式 post 或者get
                url: url,//提交到那里
                data: {parentId:parentId},
                dataType:'json',
                success:function(data){
                    if(data.status == 1){
                        if(level == 2){
                            $("#city").empty();
                            $("#city").append("<option value='' selected>选择城市</option>");
                            $("#town").empty();
                            $("#town").append("<option value='' selected>选择区县</option>");
                            var str = "";
                            $.each(data.info,function(index,array){
                                var str = "<option value='"+array['ci_id']+"'>"+array['ci_name']+"</option>";
                                $("#city").append(str);
                            });
                        }else if(level == 3){
                            $("#town").empty();
                            $("#town").append("<option value='' selected>选择区县</option>");
                            var str = "";
                            $.each(data.info, function (index, array) {
                                var str = "<option value='" + array['ci_id'] + "'>" + array['ci_name'] + "</option>";
                                $("#town").append(str);
                            });
                        }else if(level == 4){
                            $("#county").empty();
                            $("#county").append("<option value='' selected>选择乡镇</option>");
                            $("#street").empty();
                            $("#street").append("<option value='' selected>选择街道</option>");
                            var str = "";
                            $.each(data.info, function (index, array) {
                                var str = "<option value='" + array['ci_id'] + "'>" + array['ci_name'] + "</option>";
                                $("#county").append(str);
                            });
                        }else if(level == 5){
                            $("#street").empty();
                            $("#street").append("<option value='' selected>选择街道</option>");
                            var str = "";
                            $.each(data.info, function (index, array) {
                                var str = "<option value='" + array['ci_id'] + "'>" + array['ci_name'] + "</option>";
                                $("#street").append(str);
                            });
                        }
                    }else{
                        layer.msg(data.info, {icon: 5,time:1500});
                    }
                    //更新数据
                    form.render();
                },
                error:function(data){
                    console.log(data);
                }
            });

        });
    });
};
/**
 * 上传封装
 * @param string id 触发id，如：#photo
 * @param string preview 预览img的id，如：#demo
 * @param string imgVal 保存已上传图片的input中name名，如：#image
 * @param string url 上传接口地址
 */
common.uploadFile = function(data){
    /*示例数据
    data = [
        {"id":"#photo", "preview":"#demo", "val":"#image", "fileType":"file", "url":"{:url('Carousel/carouselUpload')}"}
    ]*/
    layui.use('upload', function(){
        var upload = layui.upload;
        //执行实例
        data.forEach(function(item, index){
			//默认images
            if(!item.fileType) item.fileType = "images";
            //执行上传
            upload.render({
                elem: item.id //绑定元素
                ,url: item.url //上传接口
				,accept: item.fileType //允许上传的文件类型
                ,before: function(obj){
                    //预读本地文件示例，不支持ie8
                    obj.preview(function(index, file, result){
                        //分割
                        var fileType = file.type.split("/");
                        //判断
                        if(fileType[0] == "image"){
                            var image = '<img style="width: 100%" src="'+result+'" class="layui-upload-img" />';
                            $(item.preview).html(image);
                        }else{
                            $(item.preview).html(file.name);
                        }
                    });
                }
                ,done: function(res){
                    //上传完毕回调
                    if(res.status == 1){
                        $(item.val).val(res.src);
                        console.log(item.val)
                        layer.msg(res.info, {icon: 6,time:1500});
                    }else{
                        //失败清空预览
                        $(item.preview).empty();
                        layer.msg(res.info, {icon: 5,time:1500});
                    }
                }
                ,error: function(){
                    //请求异常回调
                }
            });
        });
    });
};
/**
 * tinymce 富文本编辑器
 * @param string id dom的id名
 * @param int height 编辑器高度
 * @param string url 插入图片上传路径 {:url('Index/tinymceImgUpload')}
 */
common.tinymce = function(id, height, url){
    layui.extend({
        tinymce: "/static/tinymce/tinymce"
    }).use(['tinymce', 'util', 'layer'], function () {
        var tinymce = layui.tinymce
        // 其余配置可参考官方文档
        tinymce.render({
            elem: id,
            height: height,
            images_upload_url: url, //上传图片地址
            images_upload_base_path: "/upload/tinymce/",
            form:{name:'file'}, //配置上传文件的字段名称
            setup:function(e){ //输入时触发
                e.on('NodeChange Change KeyUp SetContent', function (){
                    $(id).val(tinymce.get(id).getContent()) //将内容保存到对应id中
                })
            },
        }, function(opt, edit){
            //加载完成后回调
        });
    });
};
/**
 * 表格分级竖形菜单显示
 * @param int string left 左边距
 */
common.tableVertical = function(left=30){
    /** 格式 <tr cate-id="{$vo.bm_id}" fid="{$vo.bm_pid}" level="{$vo.level}" > */
    //获取所有cate-id
    $("tbody tr").each(function () {
        var cateIds = $(this).attr("cate-id");
        var fid = $(this).attr("fid")
        //显示所有栏目
        for (var i in cateIds) {
            var cate = $("tbody tr[cate-id=" + cateIds + "]");
            //非顶级菜单增加边距
            var marginLeft;
            //所在层次，对应多少左内边距
            fid != 0 ? marginLeft = cate.attr('level') * left : marginLeft = cate.attr('level') * (left / 2);
            cate.find('.x-show').css('margin-left', marginLeft + 'px');
        }
    });
};
/**
 * 弹窗询问框后执行跳转
 * @param string alert 提示内容
 * @param string url 跳转链接
 */
common.alertWindow = function(alert, url){
    layer.confirm(alert,function(){
        window.location.href = url;
    });
};
/**
 * 关闭弹出层
 */
common.closeWindow = function(){
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
};
/**
 * 关闭弹出层并刷新
 */
common.closeWindowReload = function(){
    parent.location.reload();
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
};
